<script setup lang="ts">
import { ref } from 'vue'
import type { FormItemProps, FormProps, FormInstance } from 'element-plus'
import type { AddRoleType, RoleInfo } from '@/types/role'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Edit, Delete } from '@element-plus/icons-vue'
import { assignRoleAuthApi, getRoleListApi, RemoveRoleApi, updateRoleApi } from '@/apis/role'
import { RemoveUserApi } from '@/apis/login'
import type { getAuthApi } from '@/types/auth'
import { getAuthListApi } from '@/apis/auth'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { ElTree } from 'element-plus'
const router = useRouter()
const labelPosition = ref<FormProps['labelPosition']>('right')
const itemLabelPosition = ref<FormItemProps['labelPosition']>('')
const roleForm = ref({
  pagenum: 1,
  pagesize: 5,
  role_name: '',
})

//获取角色列表
const roleList = ref([] as RoleInfo[])
const getRoleList = async () => {
  const res = await getRoleListApi(roleForm.value)
  roleList.value = res.data.list as RoleInfo[]
  totalList.value = res.data.total as number
}
getRoleList()

//删除角色
const removeRole = async (row: RoleInfo) => {
  // console.log(row)
  const flag = await ElMessageBox.confirm('确定要删除该用户吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    // 响应成功在flag中,失败在catch中
  }).catch((error) => error)
  // 如果用户点击取消,就结束.否则就删除
  if (flag === 'cancel') return

  const res = await RemoveRoleApi(row)
  if (res.data.state !== 200) {
    return ElMessage.error(res.data.msg)
  }
  ElMessage.success('删除角色成功')
  // 重新调用获取用户数据
  getRoleList()
}
// 添加
const addCreateRole = () => {
  //跳转到创建角色页面
  router.push('/role/create')
}

// 重置筛选数据
const resetRole = () => {
  roleForm.value = {
    pagenum: 1,
    pagesize: 5,
    role_name: '',
  }
  getRoleList()
}

// 分页
const totalList = ref()
// 每页显示数据发生改变
const handleSizeChange = (newSize: number) => {
  roleForm.value.pagesize = newSize
  getRoleList()
}
// 跳到当前页码
const handleCurrentChange = (newPage: number) => {
  roleForm.value.pagenum = newPage
  getRoleList()
}
// 效验规则
const fromRules = {
  role_name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
}
//角色编辑对话框
const editForm = ref()

// 角色编辑
let editRoleVisible = ref(false)
const formRef = ref()
let editRole = (row: AddRoleType) => {
  //1.弹出框显示
  editRoleVisible.value = true
  /*2.用户数据回显
      2.1可以通过作用域插槽传参的形式得到用户的信息(当前项目)
      2.2 可以通过用户id,发送ajax请求获取当前用户的数据
  */
  editForm.value = row
}
//3.用户更新
const updateRole = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    // console.log(2)

    // ajax更新用户
    const res = await updateRoleApi(editForm.value as AddRoleType)
    console.log(11)

    // 更新失败
    if (res.data.state !== 200) {
      ElMessage.error(res.data.msg)
    }

    // 更新成功
    ElMessage.success('更新成功')

    // 关闭对话框
    editRoleVisible.value = false

    // 重新获取数据
    getRoleList()
  })
}
// 重置数据并移除数据不合法提示
const resetEditRole = () => {
  formRef.value.resetFields()
}

//弹出框关闭
const handleEditClose = () => {
  resetEditRole()
}
// 分配角色抽屉弹出框
// 获取权限列表
const authList = ref([] as getAuthApi[])
const getAuthList = async () => {
  const res = await getAuthListApi()
  authList.value = res.data.data as getAuthApi[]
  // console.log(authList.value)
}
getAuthList()

const assignAuthVisible = ref(false)
const assignAuthInfo = ref({
  role_name: '',
  role_id: '',
  auth_ids: '',
  auth_ids_son: '',
})
//分配权限
const assignAuth = (row: any) => {
  //1.打开抽屉弹出框
  assignAuthVisible.value = true
  // 2.数据回显
  assignAuthInfo.value.role_name = row.role_name
  assignAuthInfo.value.role_id = row.role_id
  assignAuthInfo.value.auth_ids = row.auth_ids
  assignAuthInfo.value.auth_ids_son = row.auth_ids_son
}

// 3.更新权限
const auth_ids = [] as number[]
const auth_ids_son = [] as number[]
const treeRef = ref()
const updateAuth = async () => {
  const checkNodes = treeRef.value!.getCheckedNodes(false, false)
  checkNodes.forEach((item: any) => {
    // 所有的子
    if (item.auth_pid !== 0) auth_ids_son.push(item.auth_id)
    // 父+子
    if (item.auth_pid !== 0) auth_ids.push(item.auth_pid)
    auth_ids.push(item.auth_id)
  })
  // 给auth_ids中的数据去重
  assignAuthInfo.value.auth_ids = [...new Set(auth_ids)].join()
  assignAuthInfo.value.auth_ids_son = auth_ids_son.join()

  const res = await assignRoleAuthApi(assignAuthInfo.value)
  console.log(res)

  assignAuthVisible.value = false
  ElMessage.success('更新成功')
  getRoleList()
}
</script>

<template>
  <!-- 角色筛选区 -->
  <el-card style="max-width: 100%">
    <el-form :inline="true" :model="roleForm">
      <el-form-item label="角色名">
        <el-input v-model="roleForm.role_name" placeholder="请输入角色名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="margin-left: 50px" @click="getRoleList">搜索</el-button>
        <el-button @click="resetRole">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!--角色列表  -->
  <el-card style="max-width: 100%">
    <el-button type="danger">批量删除</el-button>
    <el-button type="primary" @click="addCreateRole">添加</el-button>

    <el-table :data="roleList" style="width: 100%" boder stripe>
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="role_id" label="角色编号" width="150" />
      <el-table-column prop="role_name" label="角色名称" width="120" />
      <el-table-column prop="role_desc" label="角色描述" width="120" />

      <el-table-column prop="created_at" label="创建于" width="120" />
      <el-table-column prop="updated_at" label="更新于" width="120" />
      <el-table-column fixed="right" label="操作" width="270">
        <template v-slot="{ row }">
          <el-button
            type="primary"
            :icon="Edit"
            size="small"
            @click="editRole(row)"
            v-auth="{ name: '用户编辑' }"
          />
          <el-button type="success" size="small" @click="assignAuth(row)">分配角色</el-button>
          <el-button
            type="danger"
            :icon="Delete"
            size="small"
            @click="removeRole(row)"
            v-auth="{ name: '用户删除' }"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 分页 -->
  <el-card>
    <el-pagination
      v-model:current-page="roleForm.pagenum"
      v-model:page-size="roleForm.pagesize"
      :page-sizes="[2, 5, 10, 20]"
      size="default"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="Number(totalList)"
      @size-change="handleSizeChange(roleForm.pagesize)"
      @current-change="handleCurrentChange(roleForm.pagenum)"
    />
  </el-card>

  <!-- 编辑角色弹出框 -->
  <el-dialog v-model="editRoleVisible" title="编辑角色" width="800" @close="handleEditClose">
    <el-form ref="formRef" :model="editForm" label-width="auto" size="large" :rules="fromRules">
      <el-form-item label="角色名称" prop="username">
        <el-input v-model="editForm.role_name"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="password">
        <el-input v-model="editForm.role_desc" placeholder="请输入角色描述"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="updateRole">更新用户</el-button>
        <el-button @click="resetEditRole"> 重置 </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 角色分配权限抽屉弹出框 -->
  <el-drawer v-model="assignAuthVisible" title="分配权限" direction="rtl" v-if="assignAuthVisible">
    <el-form>
      <el-form-item label="角色名称">
        <el-input v-model="assignAuthInfo.role_name" disabled></el-input>
      </el-form-item>

      <el-form-item label="菜单权限">
        <!--  :props 配置选项,data:数据展示,:default-checked-keys:默认选中  -->
        <el-tree
          :data="authList"
          node-key="auth_id"
          :props="{ label: 'auth_name', children: 'children' }"
          :default-checked-keys="assignAuthInfo.auth_ids_son.split(',')"
          show-checkbox
          ref="treeRef"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateAuth">立即分配</el-button>
        <el-button @click="assignAuthVisible = false">返回</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped lang="scss">
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
